//
//  MTCHomePageViewController.m
//  ERP
//
//  Created by goldeney on 15/1/15.
//  Copyright (c) 2015年 ShangHai Goldeneye Techonology Co.,Ltd. All rights reserved.
//

#import "MTCContractListViewController.h"
#import "MJRefresh.h"
#import "MTContractListViewCell.h"
#import "UITableView+Custom.h"
#import "UIView+AssistView.h"
#import "LrdSuperMenu.h"
#import "NSKeyedArchiverUserLogin.h"

#import "NSDictionary+DataFormat.h"
#import "WebServiceCommonRequest.h"

#import "MTCContractDetailViewController.h"
#import "MTCSearchContractViewController.h"
#import "MTCCreateContractViewController.h"

@interface MTCContractListViewController () <LrdSuperMenuDataSource, LrdSuperMenuDelegate>

@property (strong, nonatomic) NSMutableArray *resultData;
@property (nonatomic, strong) LrdSuperMenu *menu;
@property (strong, nonatomic) NSArray *screenArray;

@property (assign, nonatomic) NSString *hzxzString;
@property (assign, nonatomic) NSString *shztString;
@property (assign, nonatomic) NSString *ffztString;
@property (assign, nonatomic) NSString *hzsqString;

@end

@implementation MTCContractListViewController
@synthesize tableView = _tableView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [self setTitle: @"营销合同"];
        
//        UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:@"新增" style:UIBarButtonItemStyleDone target:self action:@selector(createContractSelector:)];
//        self.navigationItem.rightBarButtonItem = leftButton;
        
        //设置搜索按钮
        UIButton* righButtont= [UIButton buttonWithType:UIButtonTypeCustom];
        righButtont.frame = CGRectMake(0, 0, 44, 44);
        [righButtont setImage:[UIImage imageNamed:@"home_nav_left_serch"] forState:UIControlStateNormal];
        [righButtont addTarget:self action:@selector(searchContractSelector:) forControlEvents:UIControlEventTouchUpInside];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:righButtont];
        
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    //审核状态='' --1:未审核;2:已审核
    //合同状态='' --1:待授权;2:已授权;3:已终止
    //合同性质='' --1:正式合同;2:临时合同;3:现金合同;
    //分发状态='' --0:未分发;1:已分发
    self.screenArray = @[@[@[@"不限性质",@""],@[@"正式合同",@"1"],@[@"临时合同",@"2"],@[@"现金合同",@"3"]],
                         @[@[@"不限审核",@""],@[@"已审核",@"2"],@[@"未审核",@"1"]],
                         //@[@[@"不限分发",@""],@[@"已分发",@"1"],@[@"未分发",@"0"]],
                         @[@[@"不限启用",@""],@[@"已启用",@"2"],@[@"未启用",@"1"],@[@"已停用",@"3"]]];
    
    self.hzxzString = @"";//合同性质
    self.shztString = @"";//审核状态
    self.ffztString = @"";//分发状态
    self.hzsqString = @"";//合同状态
    
    self.resultData = [NSMutableArray array];
    self.tableView.tableFooterView= [[UIView alloc] init];
    
    //添加下拉加载数据
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    
    _menu = [[LrdSuperMenu alloc] initWithOrigin:CGPointMake(0, 0) andHeight:44];
    _menu.delegate = self;
    _menu.dataSource = self;
    [self.view addSubview:_menu];
    
    [self getNetWorkDataIsReresh:YES state:@1 end:@10];
    [self.tableView headerBeginRefreshing];
}

#pragma mark - LrdSuperMenuDataSource

//每个column有多少行
- (NSInteger)menu:(LrdSuperMenu *)menu numberOfRowsInColumn:(NSInteger)column
{
    NSArray *array = self.screenArray[column];
    return array.count;
}

//每个column中每行的title
- (NSString *)menu:(LrdSuperMenu *)menu titleForRowAtIndexPath:(LrdIndexPath *)indexPath
{
    NSArray *array = self.screenArray[indexPath.column];
    NSArray *valueArray = array[indexPath.row];
    return valueArray[0];
}

//有多少个column，默认为1列
- (NSInteger)numberOfColumnsInMenu:(LrdSuperMenu *)menu
{
    return self.screenArray.count;
}

//第column列，没行的image
- (NSString *)menu:(LrdSuperMenu *)menu imageNameForRowAtIndexPath:(LrdIndexPath *)indexPath
{
    return @"";
}

#pragma mark - LrdSuperMenuDelegate

- (void)menu:(LrdSuperMenu *)menu didSelectRowAtIndexPath:(LrdIndexPath *)indexPath
{
    NSArray *array = self.screenArray[indexPath.column];
    NSArray *valueArray = array[indexPath.row];
    NSString *meunType = valueArray[1];
    
    if(indexPath.column == 0) _hzxzString = meunType;//合同性质
    if(indexPath.column == 1) _shztString = meunType;//审核状态
    //if(indexPath.column == 2) _ffztString = meunType;//分发状态
    if(indexPath.column == 2) _hzsqString = meunType;//合同状态
    
    [self getNetWorkDataIsReresh:YES state:@1 end:@10];
    [self.tableView headerBeginRefreshing];
}

#pragma mark 网络获取数据

- (void)getNetWorkDataIsReresh:(BOOL)isReresh state:(NSNumber*)state end:(NSNumber*)end
{
    //@状态（全部、供毕、正供、待供）
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeGroup];
    [content setModuleType:@"HTGL_HTLB_LIST_20170117"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    
    [content addParameterKey:@"起始条数" value:state];
    [content addParameterKey:@"结束条数" value:end];
    [content addParameterKey:@"合同性质" value:_hzxzString];
    [content addParameterKey:@"审核状态" value:_shztString];
    [content addParameterKey:@"合同状态" value:_hzsqString];
    [content addParameterKey:@"分发状态" value:_ffztString];
    [content addParameterKey:@"客户编号" value:@""];
    [content addParameterKey:@"检索条件" value:@""];
    [content addParameterKey:@"合同ID" value:@""];
    
    UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
    [content addParameterKey:@"用户ID" value:userInfo.Id];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        [self.view removeAllCustomFromSuperview];
        if(isReresh) [self.tableView headerEndRefreshing];
        else [self.tableView footerEndRefreshing];
        
        //添加数据，刷新页面
        NSArray *firstArray = nil;
        if(result.resultArray && result.resultArray.count>0)
            firstArray = [result.resultArray firstObject];
        
        if(isReresh) [self.resultData removeAllObjects];
        if(firstArray && firstArray.count>0){
            [self.resultData addObjectsFromArray:firstArray];
            [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
            [self.tableView reloadData];
        } else if(isReresh){
            [self.tableView setTableViewNotDataDrawText:@"暂无合同" isShow:YES];
        }
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [self.view removeAllCustomFromSuperview];
        if(isReresh)[self errorInfoViewText:@"哦，出错了"];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [self.view removeAllCustomFromSuperview];
        if(isReresh)[self errorInfoViewText:@"无法连接网络"];
    }];
    
}

- (void)errorInfoViewText:(NSString*)label
{
    [self.tableView headerEndRefreshing];
    [self.tableView footerEndRefreshing];
    
    if (self.tableView.visibleCells.count <= 0) {
        [self.tableView setTableViewNotDataDrawText:label isShow:YES];
    } else {
        [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
        [self showErrorHUDText:label];
    }
}

#pragma mark 开始进入刷新状态

- (void)headerRereshing
{
    NSNumber *stateNumber = [NSNumber numberWithInteger:0];
    NSNumber *endNumber = [NSNumber numberWithInteger:10];
    [self getNetWorkDataIsReresh:YES state:stateNumber end:endNumber];
}

- (void)footerRereshing
{
    NSNumber *stateNumber = [NSNumber numberWithInteger:self.resultData.count + 1];
    NSNumber *endNumber = [NSNumber numberWithInteger:self.resultData.count + 10];
    [self getNetWorkDataIsReresh:NO state:stateNumber end:endNumber];
}

#pragma mark - Table view data source

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (tableView == self.tableView) {
        return @"";
    } else {
        return @" 消息搜索结果";
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.resultData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifierOne = @"MTContractListViewCell";
    MTContractListViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifierOne];
    if (!cell)
        cell = [[MTContractListViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifierOne];
    
    NSDictionary *model = [self.resultData objectAtIndex:indexPath.row];
    cell.HTBHLabel.text = [model objectFormatStringForKey:@"合同编号" defaults:@"未知"];
    cell.HTMCLabel.text = [model objectFormatStringForKey:@"合同名称" defaults:@"未知"];
    cell.HTXZLabel.text = [model objectFormatStringForKey:@"合同性质" defaults:@"未知"];
    cell.LJFLLabel.text = [model objectFormatStringForKey:@"合同总量" format:@"累计%@方" defaults:@"未知"];
    
//    if(self.segmentActionState == ContractListSH){
//        cell.HTJDLabel.text = [model objectFormatStringForKey:@"审核状态" defaults:@"未知"];
//        cell.threeLabel.text = [model objectFormatStringForKey:@"审核人员" defaults:@"未知"];
//        cell.fourLabel.text = [model objectFormatStringForKey:@"审核日期" defaults:@"未知"];
//        cell.rightFourLabel.text = [model objectFormatStringForKey:@"合同状态" defaults:@"未知"];
//        cell.threeNameLabel.text = @"审核人员：";
//        cell.fourNameLabel.text = @"审核日期：";
//        
//    } else if(self.segmentActionState == ContractListFF){
//        cell.HTJDLabel.text = [model objectFormatStringForKey:@"分发状态" defaults:@"未知"];
//        cell.threeLabel.text = [model objectFormatStringForKey:@"业务人员" defaults:@"未知"];
//        cell.fourLabel.text = [model objectFormatStringForKey:@"签订日期" defaults:@"未知"];
//        cell.rightFourLabel.text = [model objectFormatStringForKey:@"合同状态" defaults:@"未知"];
//        
//    } else if(self.segmentActionState == ContractListSQ){
//        cell.HTJDLabel.text = [model objectFormatStringForKey:@"合同状态" defaults:@"未知"];
//        cell.threeLabel.text = [model objectFormatStringForKey:@"修改人" defaults:@"未知"];
//        cell.fourLabel.text = [model objectFormatStringForKey:@"修改日期" defaults:@"未知"];
//        cell.rightFourLabel.text = [model objectFormatStringForKey:@"审核状态" defaults:@"未知"];
//        cell.threeNameLabel.text = @"修改人员：";
//        cell.fourNameLabel.text = @"授权日期：";
//        
//    } else {
        //cell.HTJDLabel.text = [model objectFormatStringForKey:@"完成进度" format:@"%@%%" defaults:@"未知"];
        cell.HTJDLabel.text = [model objectFormatFloatStringForKey:@"完成进度" retain:1 format:@"%@%%"];
        cell.threeLabel.text = [model objectFormatStringForKey:@"业务人员" defaults:@"未知"];
        cell.fourLabel.text = [model objectFormatStringForKey:@"签订日期" defaults:@"未知"];
        cell.rightFourLabel.text = [model objectFormatStringForKey:@"合同状态" defaults:@"未知"];
//    }
    
    return cell;
}

#pragma mark
#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 82;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *model = [self.resultData objectAtIndex:indexPath.row];
    
    MTCContractDetailViewController *viewController = [[MTCContractDetailViewController alloc] initWithModel:model isAllowOperate:YES];
    viewController.backResultDelagate = self;
    [self.navigationController pushViewController:viewController animated:YES];
}

#pragma mark -
#pragma mark BackResultDataDelagate

- (void) backResultDataKey:(id)key dataValue:(id)backValue
{
    //删除合同
    if (key && backValue && [key isEqualToString:@"Delete"]) {
        [self.resultData removeObject:backValue];
        [self.tableView reloadData];
        
        if (self.resultData.count <= 0)
        [self.tableView setTableViewNotDataDrawText:@"暂无合同" isShow:YES];
        
    } else if([key isEqualToString:@"Check"]){
        //合同审核
        NSArray *originalArray = backValue;
        if (!originalArray[1]) return;
        
        NSInteger index = [self.resultData indexOfObject:originalArray[0]];
        if(index > self.resultData.count){
            [self.resultData insertObject:originalArray[1] atIndex:0];
        } else {
            [self.resultData removeObjectAtIndex:index];
            [self.resultData insertObject:originalArray[1] atIndex:index];
        }
        [self.tableView reloadData];
        if (self.resultData.count <= 0)
            [self.tableView setTableViewNotDataDrawText:@"暂无合同" isShow:YES];
        
    } else if([key isEqualToString:@"Modif"]){
        //合同修改
        NSArray *originalArray = backValue;
        if (!originalArray[1]) return;
        
        NSInteger index = [self.resultData indexOfObject:originalArray[0]];
        if(index > self.resultData.count){
            [self.resultData insertObject:originalArray[1] atIndex:0];
        } else {
            [self.resultData removeObjectAtIndex:index];
            [self.resultData insertObject:originalArray[1] atIndex:index];
        }
        [self.tableView reloadData];
        if (self.resultData.count <= 0)
            [self.tableView setTableViewNotDataDrawText:@"暂无合同" isShow:YES];
        
    } else if([key isEqualToString:@"AuthContract"]){
        //合同授权
        NSArray *originalArray = backValue;
        if (!originalArray[1]) return;
        
        NSInteger index = [self.resultData indexOfObject:originalArray[0]];
        if(index > self.resultData.count){
            [self.resultData insertObject:originalArray[1] atIndex:0];
        } else {
            [self.resultData removeObjectAtIndex:index];
            [self.resultData insertObject:originalArray[1] atIndex:index];
        }
        
        [self.tableView reloadData];
        if (self.resultData.count <= 0)
            [self.tableView setTableViewNotDataDrawText:@"暂无合同" isShow:YES];
        
    } else if([key isEqualToString:@"StopContract"]){
        //合同终止
        NSArray *originalArray = backValue;
        if (!originalArray[1]) return;
        
        NSInteger index = [self.resultData indexOfObject:originalArray[0]];
        if(index > self.resultData.count){
            [self.resultData insertObject:originalArray[1] atIndex:0];
        } else {
            [self.resultData removeObjectAtIndex:index];
            [self.resultData insertObject:originalArray[1] atIndex:index];
        }
        
        [self.tableView reloadData];
        if (self.resultData.count <= 0)
            [self.tableView setTableViewNotDataDrawText:@"暂无合同" isShow:YES];
        
    } else if([key isEqualToString:@"Distribute"]){
        //合同分发
        NSArray *originalArray = backValue;
        if (!originalArray[1]) return;
        
        NSInteger index = [self.resultData indexOfObject:originalArray[0]];
        if(index > self.resultData.count){
            [self.resultData insertObject:originalArray[1] atIndex:0];
        } else {
            [self.resultData removeObjectAtIndex:index];
            [self.resultData insertObject:originalArray[1] atIndex:index];
        }
        [self.tableView reloadData];
        if (self.resultData.count <= 0)
            [self.tableView setTableViewNotDataDrawText:@"暂无合同" isShow:YES];
    }
    
}


#pragma mark
#pragma mark IBAction

- (void)createContractSelector:(id)selector
{
    MTCCreateContractViewController *view = [[MTCCreateContractViewController alloc] init];
    [self.navigationController pushViewController:view animated:YES];
}

- (void)searchContractSelector:(id)selector
{
    MTCSearchContractViewController *view = [[MTCSearchContractViewController alloc] init];
    AbstractNavigationController *mNavigation = [[AbstractNavigationController alloc] initWithRootViewController:view];
    [self.navigationController presentViewController:mNavigation animated:NO completion:nil];
}

@end
